package com.changxianggu.crawler.cloud.test;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.changxianggu.cloud.crawler.core.WebApplication;
import com.changxianggu.cloud.crawler.core.modules.storage.entity.CxgBook;
import com.changxianggu.cloud.crawler.core.modules.storage.service.ICxgBookService;
import com.changxianggu.cloud.crawler.core.utils.HttpUtil;
import com.changxianggu.cloud.crawler.core.utils.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {WebApplication.class})// 指定启动类
@Slf4j
public class KuangDa {

    @Autowired
    ICxgBookService bookService;

    public static final String COOKIE = "JSESSIONID=2659C3E45830AC28EE3479C2D3E5A69F";
    public static final String REFERER = "http://www.cumtp.com/search?q=";
    public static final String URL_PRE = "http://www.cumtp.com";


    @Test
    public void initCrawler() throws Exception {
        doCrawler();
    }

    public void doCrawler() throws Exception {
        int pageNum = 1;
        int totalPage = 7;
        for (int i = pageNum; i <= totalPage; i++) {
            String url = "http://www.cumtp.com/mall/list/sale-ebooks";
            Map<String, Object> parameter = MapUtil.newHashMap(1);
            parameter.put("page", i);
            Map<String, Object> headers = MapUtil.newHashMap(5);
            headers.put("Cookie", COOKIE);
            headers.put("User-Agent", UserAgentUtil.random());
            headers.put("Referer", REFERER);
            String result = HttpUtil.doGet(url, headers, parameter);
            while (result.contains("页面没有找到")) {
                //睡眠2秒继续访问
                Thread.sleep(2000);
                result = HttpUtil.doGet(url, headers);
            }
            if (StrUtil.isNotBlank(result)) {
                Document htmlDoc = Jsoup.parse(result);
                Elements bookContentList = htmlDoc.select(".col-lg-3");
                if (bookContentList != null && bookContentList.size() > 0) {
                    List<CxgBook> listBook = new ArrayList<>();
                    for (Element element : bookContentList) {
                        CxgBook bookEntity = new CxgBook();

                        Element detailElement = element.select("a").first();
                        if (detailElement != null) {
                            String href = URL_PRE + detailElement.attr("href");
                            try {
                                bookEntity = getBookEntity(href);
                            } catch (Exception e) {

                            }
                        }
                        if (StrUtil.isNotBlank(bookEntity.getBookName())) {
                            listBook.add(bookEntity);
                        }
                    }
                    bookService.saveBatch(listBook);
                    log.info("第" + i + "页数据保存成功");
                    log.warn("--->" + i);
                }
            }
        }
    }

    public CxgBook getBookEntity(String href) throws Exception {
        CxgBook bookEntity = new CxgBook();
        String url = href;
        Map<String, Object> headers = MapUtil.newHashMap(5);
        headers.put("Cookie", COOKIE);
        headers.put("User-Agent", UserAgentUtil.random());
        headers.put("Referer", REFERER);
        String result = HttpUtil.doGet(url, headers);
        while (result.contains("页面没有找到")) {
            //睡眠2秒继续访问
            Thread.sleep(2000);
            result = HttpUtil.doPost(url, headers);
        }
        if (StrUtil.isNotBlank(result) && !result.contains("商品不存在或已下架")) {
            Document htmlDoc = Jsoup.parse(result);
            Element bookContent = htmlDoc.select(".margin-top-20").eq(2).first();
            Element tempContent = htmlDoc.select(".size-12").eq(1).first();
            Element bodyContent = htmlDoc.select("body").first();
            if (bookContent != null) {
                Element nameElement = bookContent.select(".nomargin-bottom").first();
                if (nameElement != null) {
                    String name = nameElement.text();
                    bookEntity.setBookName(name);
                }

                Element authorElement = bookContent.select(".margin-top-10 .row .col-md-10").first();
                if (authorElement != null) {
                    String author = authorElement.text();
                    bookEntity.setAuthor(author);
                }

                Element isbnElement = tempContent.select(".col-lg-4").first();
                if (isbnElement != null) {
                    String isbn = isbnElement.text().replace("ISBN：","");
                    bookEntity.setBookIsbn(isbn.replace("-", ""));
                }

                Element pubDateElement = tempContent.select(".col-lg-4").eq(4).first();
                if (pubDateElement != null) {
                    String pubDateStr = pubDateElement.text();
                    if (StrUtil.isNotBlank(pubDateStr) && pubDateStr.contains("印刷时间：")) {
                        try {
                            pubDateStr = pubDateStr.replace("印刷时间：", "") + " 00:00:00";
                            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                            LocalDateTime localDateTime = LocalDateTime.parse(pubDateStr, dtf);
                            bookEntity.setPubDate(localDateTime);
                        } catch (Exception e) {

                        }
                    }
                }

                Element bvElement = tempContent.select(".col-lg-4").eq(1).first();
                if (bvElement != null) {
                    String bvStr = bvElement.text().replace("版次：", "");
                    bookEntity.setBookVersion(bvStr);
                }

                Element pageNumElement = tempContent.select(".col-lg-4").eq(2).first();
                if (pageNumElement != null) {
                    String pageNumStr = pageNumElement.text().replace("页数：", "");
                    try {
                        bookEntity.setPageNum(Integer.parseInt(pageNumStr));
                    } catch (Exception e) {

                    }
                }

                Element wordNumElement = tempContent.select(".col-lg-4").eq(3).first();
                if (wordNumElement != null) {
                    String wordNumStr = wordNumElement.text().replace("字数：", "");
                    try {
                        bookEntity.setWordNum(Integer.parseInt(wordNumStr));
                    } catch (Exception e) {

                    }
                }

                Element pvElement = tempContent.select(".col-lg-4").eq(6).first();
                if (pvElement != null) {
                    String pvNumStr = pvElement.text().replace("印次：", "");
                    try {
                        bookEntity.setPrintVersion(pvNumStr);
                    } catch (Exception e) {

                    }
                }

                Element imgElement = bodyContent.select("#zoom-primary").first();
                Element coverElement = imgElement.select("img").first();
                if (coverElement != null) {
                    String srcStr = URL_PRE + coverElement.attr("src");
                    bookEntity.setCover(srcStr);
                }

                Element priceElement = bookContent.select(".shop-item-price").first();
                if (priceElement != null) {
                    String priceStr = priceElement.text().trim().replace("¥", "");
                    if (StrUtil.isNotBlank(priceStr)) {
                        try {
                            bookEntity.setPrice(new BigDecimal(priceStr));
                        } catch (Exception e) {

                        }
                    }
                }

                Element digUriElement = bodyContent.select(".btn-success").first();
                if (digUriElement != null) {
                    String digUriStr = digUriElement.attr("href");
                    if (StrUtil.isNotBlank(digUriStr)) {
                        bookEntity.setDigitalUri(URL_PRE+ digUriStr);
                    }
                }

                //catalog
                Element catalogElement = bodyContent.select("#description .row").last();
                if (catalogElement != null) {
                    String catalogStr = catalogElement.text();
                    if (StrUtil.isNotBlank(catalogStr)) {
                        bookEntity.setCatalog(catalogStr);
                    }
                }

                //brief
                Element briefElement = bodyContent.select("#description .col-lg-12").eq(1).first();
                if (briefElement != null) {
                    String briefStr = briefElement.select("p").text();
                    if (StrUtil.isNotBlank(briefStr)) {
                        bookEntity.setBrief(briefStr);
                    }
                }

                bookEntity.setPkId(getNumbers(href));
                bookEntity.setIsSync(0);
                bookEntity.setCreateTime(LocalDateTime.now());
                bookEntity.setPressName("中国矿业大学出版社");
                bookEntity.setStatus(1);
                //出版社Id不明
                bookEntity.setPressId(127);
            }
        }
        return bookEntity;
    }

    /**
     * 判断一个字符串是否都为数字
     *
     * @param strNum
     * @return
     */
    public boolean isDigit(String strNum) {
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher((CharSequence) strNum);
        return matcher.matches();
    }

    /**
     * 截取数字
     *
     * @param content
     * @return
     */
    public String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }

    /**
     * 截取字符串str中指定字符 strStart、strEnd之间的字符串
     *
     * @return
     */
    public String subString(String str, String strStart, String strEnd) {

        /* 找出指定的2个字符在 该字符串里面的 位置 */
        int strStartIndex = str.indexOf(strStart);
        int strEndIndex = str.indexOf(strEnd);

        /* index 为负数 即表示该字符串中 没有该字符 */
        if (strStartIndex < 0) {
            return "";
        }
        if (strEndIndex < 0) {
            return "";
        }
        /* 开始截取 */
        String result = str.substring(strStartIndex, strEndIndex).substring(strStart.length());
        return result;
    }
}
